var oMedia = {
	iFolderId : 0
}


function remove_iframe() {
	$('#media_edit_media_iframe').remove();
	$('#dgi_overlay').remove();
	
	get_folder_media(oMedia.iFolderId);
}


function set_uploaded_media_folder_id() {
	$.post('/admin/media_ajax/set_uploaded_media_folder_id/', { iFolderId : oMedia.iFolderId }, function(data) {
		get_folder_media(oMedia.iFolderId);
	}, 'json');
}


function get_folder_path(oObj) {
	var bParent = true;
	var aPath = new Array();
	var iPath = 0;
	var sFolderText;
	var iFolderId;
	var i = 0;
	var sFolderPath = '';
	
	while (bParent) {
		
		sFolderText = $(oObj).text();
		
		if (sFolderText == '') {
			bParent = false;
		} else {
		
			aPath[iPath] = new Object();
			aPath[iPath]['title'] = sFolderText;
			aPath[iPath]['folder_id'] = iFolderId;
			
			iPath++;
			
			oObj = $(oObj).parent().parent().parent().children('span');
		}
		
	}
	
	iPath = aPath.length;
	
	var oDiv = document.createElement('div');
	$(oDiv).addClass('folder_path_el');
	
	var oFolderPath;
	
	$('#media_folder_path').html('');
	
	for (i = (iPath - 1); i >= 0; i--) {
		
		oFolderPath = $(oDiv).clone();
		$(oFolderPath).html(aPath[i]['title']);
		$('#media_folder_path').append(oFolderPath);
		
	}	
	
	$(oDiv).removeClass('folder_path_el').addClass('<?php echo $this->config->item('site_accr'); ?>_clear');
	
	$('#media_folder_path').append(oDiv);
	
	//$('#mm_folder_path').html(sFolderPath);	
};


function get_folder_media(iFolderId) {
	$.post('/admin/media_ajax/get_folder_media/', { iFolderId : iFolderId }, function(data) {
		$('.media_title').editable('destroy');
		$('#media_media').html('').html(data.sContent);
		$('.media_title').editable('/admin/media_ajax/rename_media', {
			width: '115px',
			select: true,
			onblur: 'submit', 
			submitdata: function(o, a) {
				var iMediaId = $(this).parent().attr('id').replace('media_item_', '');
				return { iMediaId : iMediaId };
			},
			ajaxoptions: {
				dataType: 'json'
			},
			callback: function(value, settings) {
				$(this).html(value.sMediaTitle);
			}
		});
	}, 'json');
}



function edit_media(iMediaId) {
	create_overlay(null, function(sId, oImg, oParams) {
		var oIframe = document.createElement('iframe');
		
		var iMarginLeft = 20;
		var iMarginTop = 20;
		
		var iHeight = $(document).height() - (iMarginTop * 2);
		var iWidth = $(document).width() - (iMarginLeft * 2);
		
		$(oIframe).css({
			marginLeft: iMarginLeft + 'px',
			marginTop: iMarginTop + 'px',
			width: iWidth + 'px',
			height: iHeight + 'px', 
			border: '2px solid #333'
		}).attr({
			id : 'media_edit_media_iframe',
			src : '/admin/media/edit_media/media_id/' + oParams.iMediaId
		}).appendTo(document.body);

		$(oIframe).load(function() {
			$(oImg).remove();
			$(oIframe).show();
			$('#' + sId).remove();
		});

	}, { iMediaId : iMediaId });
}


function delete_media(iMediaId) {
	create_overlay(null, function(sId, oImg, oParams) {
		$.post('/admin/media_ajax/delete_media', oParams, function(data) {
			if (data.iMatches === 0) {
				$(oImg).remove();
				$('#' + sId).remove();
				
				$.prompt('<?php echo $aMessages['admin_media_confirm_delete']; ?>', {
					buttons : {
						yes : true,
						no : false
					},
					callback : function(bReturn) {
						if (bReturn === true) {
							confirm_delete_media(iMediaId);
							
						}
					}
				});
			}
		}, 'json');
	}, { iMediaId : iMediaId });
}



function confirm_delete_media(iMediaId) {
	create_overlay(null, function(sId, oImg, oParams) {
		$.post('/admin/media_ajax/confirm_delete_media', oParams, function(data) {
			if (data.sDone) {
				$(oImg).remove();
				$('#' + sId).remove();

				$('#media_item_' + oParams.iMediaId).animate({
					width: '0px'
				}, 500, 'linear', function() {
					$(this).remove();
					
					if ($('.media_item').length === 0) {
						get_folder_media(oMedia.iFolderId);
					}
				});
			}
		}, 'json');
	}, { iMediaId : iMediaId });

}


function get_folder_form(iParentFolderId, iFolderId, sAction) {
	
	iFolderId = iFolderId || '0';
	sAction = sAction || 'add';

	create_overlay(null, function(sId, oImg, oParams) {
		
		oParams.sOverlayId = sId;
	
		$.post('/admin/media_ajax/get_folder_form/', oParams, function(data) {
			$(oImg).replaceWith(data.sContent);
		}, 'json');
	
	}, { iParentFolderId : iParentFolderId, iFolderId : iFolderId, sAction : sAction });
}


function add_folder(sOverlayId) {
	var iParentFolderId = $('#iParentFolderId').val();
	var sFolderTitle = $('#media_folder_title').val();
	
	if (val_is_empty(sFolderTitle) === true) {
		$.prompt('<?php echo addslashes($aMessages['admin_media_enter_folder_name']); ?>');
		return;
	}
	
	
	$('#media_folder').remove();
	
	create_overlay(sOverlayId, function(sId, oImg, oParams) {
		
		$.post('/admin/media_ajax/add_folder/', oParams, function(data) {
			
			if(data.sContent) {
				$('#media_folders').html(data.sContent);
			}
			
			$('#' + sId).remove();
			$(oImg).remove();
			
			return;			
		}, 'json');
		
	}, { iParentFolderId : iParentFolderId, sFolderTitle : sFolderTitle });
}


function rename_folder(sOverlayId) {
	var iFolderId = $('#iFolderId').val();
	var sFolderTitle = $('#media_folder_title').val();
	
	if (val_is_empty(sFolderTitle) === true) {
		$.prompt('<?php echo addslashes($aMessages['admin_media_enter_folder_name']); ?>');
		return;
	}
	
	
	$('#media_folder').remove();
	
	create_overlay(sOverlayId, function(sId, oImg, oParams) {
		
		$.post('/admin/media_ajax/rename_folder/', oParams, function(data) {
			
			if(data.iFolderId && data.sFolderTitle) {
				$('#folder_'+data.iFolderId+' a').html(data.sFolderTitle);
			}
			
			$('#' + sId).remove();
			$(oImg).remove();
			
			
		}, 'json');
		
	}, { iFolderId : iFolderId, sFolderTitle : sFolderTitle });
}

function check_delete_folder(iFolderId) {
	$.post('/admin/media_ajax/check_delete_folder', {'iFolderId' : iFolderId}, function(d){
		
		if(d.iMedia > 0) {
			
			$.prompt('This folder still has media in. Please delete all media within this folder before deleting.');
			
		} else if(d.iChildFolders > 0) {
			
			$.prompt('This folder still has sub folders. Please delete all sub folders within this folder before deleting.');
			
		} else {
			
			$.prompt('Are you sure you want to delete this folder?', {
				buttons : {
					yes : true,
					no : false
				},
				callback : function(bReturn) {
					if (bReturn === true) {
						confirm_delete_folder(iFolderId);
					}
				}
			});
			
		}
		
	}, 'json');
}

function confirm_delete_folder(iFolderId) {
	create_overlay(null, function(sId, oImg, oParams) {
		$.post('/admin/media_ajax/confirm_delete_folder', oParams, function(data) {
			if (data.sDone && data.sDone == 'Y') {
				$(oImg).remove();
				$('#' + sId).remove();
			}
		}, 'json');
	}, { iFolderId : iFolderId });
}


$(document).ready(
	function() {
		$('.folder a').live('click', function(){
			var iFolderId = $(this).parent().attr('id').replace('folder_', '');
			
			$('.folder_selected').removeClass('folder_selected');
			$(this).addClass('folder_selected');
			
			oMedia.iFolderId = iFolderId;
			
			$('#media_upload_cont').show();
			
			get_folder_media(iFolderId);
		});
		
		$('.media_item').live('click', function() {
			if ($(this).hasClass('media_item_selected') === false) {
				$('#file_dimensions_wrapper').hide();
				$('.media_item_selected').removeClass('media_item_selected');
				$(this).addClass('media_item_selected');
				
				var file_name = $(this).find('.media_title').eq(0).html();
				$('#file_name').html(file_name);
				$('#file_name_wrapper').show();
				
				if($(this).find('.media_dimension_width').length == 1) {
					var media_dimensions = $(this).find('.media_dimension_width').eq(0).val() + " x " + $(this).find('.media_dimension_height').eq(0).val();
					$('#file_dimensions').html(media_dimensions);
					$('#file_dimensions_wrapper').show();
				}
			}
		});
		
		
		$('#media_upload').uploadify({
			'uploader': '/assets/flash/uploadify.swf',
			'script': '/upload/file_upload',
			'folder': '/assets/flash/tmp_upload',
			'wmode' : 'transparent',
			'auto' : true,
			'cancelImg': '/assets/images/<?php echo $this->sPlatform; ?>/admin/media/cancel.png',
			'multi' : true,
			'height' : 33, 
			'width' : 95, 
			'queueID' : 'upload_queue_container', 
			'buttonImg' : '/assets/images/web/admin/buttons/upload.png', 
			'scriptData' : { 
				'sUploadType' : 'media', 
				'iUserId' : <?php echo $this->user->userId; ?>
			},
			onSelectOnce: function() {
				$('#media_media').hide();
			},
			onAllComplete: function() {
				$('#media_media').show();
				set_uploaded_media_folder_id();
				
			},
			onError: function (a, b, c, d) {
	         	if (d.status == 404) {
	            	alert('Could not find upload script. Use a path relative to: '+'<?php getcwd() ?>');
				} else if (d.type === "HTTP") {
	            	alert('error '+d.type+": "+d.status);
				} else if (d.type ==="File Size") {
	            	alert(c.name+' '+d.type+' Limit: '+Math.round(d.sizeLimit/1024)+'KB');
	         	} else {
	            	alert('error '+d.type+": "+d.text);
				}
			}
		});
		
		
		$('#media_upload_cont').hide();
		
		
		$('.media_item').contextMenu('media_file_context', {
			bindings: {
				'edit_media': function(t) {
			   		var iMediaId = $(t).attr('id').replace('media_item_', '');
			   		edit_media(iMediaId);
				},
				'rename_media' : function(t) {
			   		var iMediaId = $(t).attr('id').replace('media_item_', '');
					
					var oMediaTitle = $(t).children('.media_title');
					
					$(oMediaTitle).trigger('click');
					
					
				},
			    'copy_file': function(t) {
			   		var iMediaId = $(t).attr('id').replace('media_item_', '');
					// TODO: TODO
					return;
					copy_move_media('Copy', iMediaId);
			    },
				'move_file': function(t) {
			   		var iMediaId = $(t).attr('id').replace('media_item_', '');
					// TODO: TODO
					return;
			    	copy_move_media('Move', iMediaId);
			    },
			        
			    'tag_file': function(t) {
			   		var iMediaId = $(t).attr('id').replace('media_item_', '');
					// TODO: TODO
					return;
			    	tag_media(iMediaId); 	
			    },
			    'delete_media': function(t) {
			   		var iMediaId = $(t).attr('id').replace('media_item_', '');
				    delete_media(iMediaId); 	
			    }
			
			}
		});
		
		$('.folder').contextMenu('folder_tree_context', {
			bindings: {
				'add_media_subfolder': function(t) {
			   		var iFolderId = $(t).attr('id').replace('folder_', '');
					
					get_folder_form(iFolderId, 'add');
				},
				'rename_media_folder': function(t) {
					var iFolderId = $(t).attr('id').replace('folder_', '');
					
					get_folder_form(0, iFolderId, 'rename');
				}, 
				'delete_media_folder': function(t) {
					var iFolderId = $(t).attr('id').replace('folder_', '');
					
					check_delete_folder(iFolderId);
				}
			}
		});
	}
);